<?php
/**
 * 小程序接口基类
 *
 */

namespace controller;

use service\ToolsService;

/**
 * 基础接口类
 * Class BasicApi
 * @package controller
 */

class BasicApi {

    const SUCESS_CODE = 200;

    /**
     * 当前请求对象
     * @var \think\Request
     */
    protected $request;

    /**
     * 构造方法
     * BasicApi constructor.
     */
    public function __construct()
    {
        ToolsService::corsOptionsHandler();
        $this->request = app('request');
    }

    /**
     * 返回成功的操作
     * @param string $msg 消息内容
     * @param array $data 返回数据
     */
    protected function success($msg, $data = [])
    {
        ToolsService::success($msg, $data);
    }

    /**
     * 返回失败的请求
     * @param string $msg 消息内容
     * @param array $data 返回数据
     */
    protected function error($msg, $data = []) {
        ToolsService::error($msg, $data);
    }

    protected function outputJsonSuccess($datas) {
        $data = array();
        $data['code'] = self::SUCESS_CODE;
        $data['data'] = $datas;
        $data['msg'] = "";

        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit();
    }

    /**
     * 默认错误编号：400
     */
    protected function outputJsonError($message='', $code=400) {
        if ($code == self::SUCESS_CODE) {
            $code = 400;
        }

        $data = array();
        $data['code'] = $code;
        $data['msg'] = $message;

        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit();
    }

    protected function createRandomNum($length) {
        $str = '0123456789';
        $strlen = 10;
        while($length > $strlen){
            $str .= $str;
            $strlen += 10;
        }
        $str = str_shuffle($str);

        return substr($str, 0, $length);
    }

    protected function createRandomStr($length) {
        $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $strlen = 62;
        while($length > $strlen){
            $str .= $str;
            $strlen += 62;
        }
        $str = str_shuffle($str);

        return substr($str, 0, $length);
    }
}